package com.wanggsx.library.base.views;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager.widget.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

import com.wanggsx.library.R;
import com.wanggsx.library.util.MethodsNetwork;
import com.wanggsx.library.util.UtilsData;
import com.wanggsx.library.util.UtilsScreen;
import com.wanggsx.library.util.UtilsToast;
import com.wanggsx.library.util.fun.UtilsGlide;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * ViewPager实现的轮播图广告自定义视图，如京东首页的广告轮播图效果； 既支持自动轮播页面也支持手势滑动切换页面
 */

public class ImageViewAdvertisement extends FrameLayout {
    // 自动轮播启用开关
    private boolean isAutoPlay = false;
    private static final String TAG = ImageViewAdvertisement.class.getSimpleName();
    // 自定义轮播图的资源
    private String[] strImageUrls = null;
    // 广告链接
    private String[] strImageLinks = null;
    // 放轮播图片的ImageView 的list
    private Map<String, ImageView> mapImageViews;
    // 放圆点的View的list
    private List<View> listDotViews;
    private ViewPager viewPager;
    // 当前展示第几页
    private int currPageIndex = 0;
    // 定时任务
    private ScheduledExecutorService scheduledExecutorService;
    private Context context;
    private String mStrTime = "";
    private String mStrMd5;
    private boolean isFrist = true;
    // Handler
    private Handler handler = null;
    private LinearLayout dotLayout;
    //状态: 0-滑动结束 1-触摸开始(滑动) 2-页面切换中
    private int mViewPagerState = 0;
    //是否无线循环,默认开启
    private boolean mIsScrollForever = true;

    public ImageViewAdvertisement(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    /**
     * 开始轮播图切换
     */
    @SuppressLint("HandlerLeak")
    private void startPlay() {
        if (strImageUrls == null || strImageUrls.length <= 1) {
            return;
        }
        if (handler == null) {
            handler = new Handler() {

                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    if (viewPager != null) {
                        if (mViewPagerState != 0) {
                            currPageIndex--;
                        } else {
                            //滑动到ViewPager指定位置
                            viewPager.setCurrentItem(currPageIndex);
                        }
                    }
                }

            };
        }
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4,
                TimeUnit.SECONDS);
    }

    public void toShow(ArrayList listImageUrls, ArrayList listLinkUrls, int[] imageIds, boolean autoPlay, boolean isShowDot, boolean isScrollForever) {
        mIsScrollForever = isScrollForever;
        mapImageViews = new HashMap<>();
        listDotViews = new ArrayList<View>();
        if (listImageUrls != null && listImageUrls.size() >= 1) {
            int size = listImageUrls.size();
            //初始化图片路径和图片链接数组
            strImageUrls = new String[size];
            strImageLinks = new String[size];
            for (int i = 0; i < size; i++) {
                strImageUrls[i] = (String) listImageUrls.get(i);
                if (listLinkUrls != null && listLinkUrls.size() >= (i + 1)) {
                    strImageLinks[i] = (String) listLinkUrls.get(i);
                } else {
                    strImageLinks[i] = "";
                }
            }
            initUI(context, null, isShowDot);
        } else {
            if (imageIds != null && imageIds.length >= 1) {
                int size = imageIds.length;
                strImageLinks = new String[size];
                for (int i = 0; i < size; i++) {
                    if (listLinkUrls != null && listLinkUrls.size() >= (i + 1)) {
                        strImageLinks[i] = (String) listLinkUrls.get(i);
                    } else {
                        strImageLinks[i] = "";
                    }
                }
            }
            initUI(context, imageIds, isShowDot);
        }
        //决定是否要实现自动播放
        isAutoPlay = autoPlay;
        if (isAutoPlay) {
            startPlay();
        }
    }

    //图片切换
    private OnImageSelectedChangeListener mPageChangedListener;

    public void setOnImageSelectedChangeListener(OnImageSelectedChangeListener mPageChangedListener) {
        this.mPageChangedListener = mPageChangedListener;
    }

    //选中
    public interface OnImageSelectedChangeListener {
        void onPageChanged(int pageIndex, int totalCount);
    }

    //图片点击事件
    private OnImageViewClickListener mListener;

    public void setOnViewClickListener(OnImageViewClickListener mListener) {
        this.mListener = mListener;
    }

    public interface OnImageViewClickListener {
        void onClick(int index, String url, String linkUrl);
    }

    //重置高度
    public void resetSizeWithHightPerWidth(final double ratHeigtPerWith) {
        getLayoutParams().height = (int) (UtilsScreen.getScreenWidth() * ratHeigtPerWith);
    }

    /**
     * 停止轮播图切换
     */
    public void stopPlay() {
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdownNow();
        }
        // handler.removeCallbacksAndMessages(null);
        handler = null;
        destroyDrawingCache();
    }

    /**
     * 初始化Views等UI
     */
    private void initUI(Context context, int[] imageIds, boolean isShowDot) {
        LayoutInflater.from(context).inflate(R.layout.layout_slideshow, this,
                true);
        dotLayout = (LinearLayout) findViewById(R.id.dotLayout);
        dotLayout.removeAllViews();
        if (strImageUrls == null || strImageUrls.length == 0) {
            //没有图片
            if (imageIds != null && imageIds.length >= 1) {
                for (int i = 0; i <= imageIds.length - 1; i++) {
                    //添加指示圆点
                    if (isShowDot) {
                        ImageView dotView = new ImageView(context);
                        dotView.bringToFront();
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                        params.leftMargin = 3;
                        params.rightMargin = 3;
                        dotLayout.addView(dotView, params);
                        dotLayout.bringToFront();
                        if (i == 0) {
                            dotView.setBackgroundDrawable(getResources().getDrawable(R.mipmap.circle_black));
                        } else {
                            dotView.setBackgroundDrawable(getResources().getDrawable(R.mipmap.circle_white));
                        }
                        listDotViews.add(dotView);
                    }
                }
            }
        } else {
            // 有图片
            for (int i = 0; i < strImageUrls.length; i++) {
                if (isShowDot) {
                    ImageView dotView = new ImageView(context);
                    dotView.bringToFront();
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                    params.leftMargin = 3;
                    params.rightMargin = 3;
                    dotLayout.addView(dotView, params);
                    dotLayout.bringToFront();
                    if (i == 0) {
                        dotView.setBackgroundDrawable(getResources().getDrawable(R.mipmap.circle_black));
                    } else {
                        dotView.setBackgroundDrawable(getResources().getDrawable(R.mipmap.circle_white));
                    }
                    listDotViews.add(dotView);
                }
            }
        }
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        //重置高度
        if (strImageUrls != null && strImageUrls.length >= 1) {
            UtilsData.resetViewHeightFitScreenWidth(context, strImageUrls[0], (ViewGroup) ((ViewGroup) viewPager.getParent().getParent()));
        }
        viewPager.setFocusable(true);
        viewPager.setAdapter(new MyPagerAdapter());
        viewPager.setOnPageChangeListener(new MyPageChangeListener());
        //changeScrollTime(viewPager);
    }

    public static void changeScrollTime(ViewPager viewPager) {
        //通过反射修改viewPage的滚动事件
        try {
            Field field = ViewPager.class.getDeclaredField("mScroller");
            field.setAccessible(true);
            FixedSpeedScroller scroller = new FixedSpeedScroller(viewPager.getContext(),
                    new AccelerateInterpolator());
            field.set(viewPager, scroller);
            scroller.setTime(500);
        } catch (Exception e) {
        }
    }

    /**
     * 填充ViewPager的页面适配器
     */
    private class MyPagerAdapter extends PagerAdapter {

        @Override
        public void destroyItem(View container, final int position, Object object) {
            Log.d("wanggsximageviews", this + " destroyItem pos=" + position);
            String strkey = position + "";
            if (mapImageViews.containsKey(strkey)) {
                ((ViewPager) container).removeView(mapImageViews.get(strkey));
                mapImageViews.remove(strkey);
            }
        }

        @Override
        public Object instantiateItem(final View container, final int pos) {
            Log.d("wanggsximageviews", this + " instantiateItem pos=" + pos);
            String strkey = pos + "";
            final int actpos = pos % strImageUrls.length;
            ImageView imageView = new ImageView(getContext());
            imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            imageView.setScaleType(ScaleType.FIT_XY);
            ((ViewPager) container).addView(imageView);
            UtilsGlide.loadImage(context, strImageUrls[actpos], imageView);
            mapImageViews.put(strkey, imageView);
            imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (MethodsNetwork.netWorkType >= 1) {
                        /*Intent intent = new Intent(context, MyWebViewActivityWithTittleBar.class);
                        intent.putExtra(MyWebViewActivityWithTittleBar.URL, strImageLinks[actpos]);
                        UtilsActivity.startActivity(intent);*/
                        if (mListener != null) {
                            mListener.onClick(actpos, strImageUrls[actpos], strImageLinks[actpos]);
                        }
                    } else {
                        UtilsToast.showShort("请连接网络!");
                    }
                }
            });
            return imageView;
        }

        @Override
        public int getCount() {
            if (mIsScrollForever) {
                return Integer.MAX_VALUE;
            } else {
                return strImageUrls == null ? 0 : strImageUrls.length;
            }
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {

        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {

        }

        @Override
        public void finishUpdate(View arg0) {

        }

    }

    /**
     * ViewPager的监听器 当ViewPager中页面的状态发生改变时调用
     */
    private class MyPageChangeListener implements OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {
            mViewPagerState = arg0;
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        //最后一次指示的位置
        private int last = 0;

        @Override
        public void onPageSelected(int pos) {
            currPageIndex = pos;
            int actpos = pos % strImageUrls.length;
            if (mPageChangedListener != null) {
                mPageChangedListener.onPageChanged(actpos, strImageUrls.length);
            }
            if (listDotViews.size() > actpos) {
                listDotViews.get(actpos).setBackgroundDrawable(getResources().getDrawable(R.mipmap.circle_black));
                listDotViews.get(last).setBackgroundDrawable(getResources().getDrawable(R.mipmap.circle_white));
                last = actpos;
            }
        }
    }

    @Override
    protected void onAttachedToWindow() {
        //恢复原来的状态
        if (scheduledExecutorService == null && isAutoPlay) {
            startPlay();
        }
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        //停止自动滚动状态
        stopPlay();
        scheduledExecutorService = null;
        super.onDetachedFromWindow();
    }

    /**
     * 执行轮播图切换任务
     */
    private class SlideShowTask implements Runnable {
        @Override
        public void run() {
            synchronized (viewPager) {
                if (mViewPagerState == 0) {
                    currPageIndex += 1;
                    handler.obtainMessage().sendToTarget();
                }
            }
        }
    }

}